<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>统一认证授权中心</h2>
        <p>欢迎登录</p>
      </div>

      <el-tabs v-model="activeTab" stretch>
        <el-tab-pane label="账号密码登录" name="password">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
            <el-form-item prop="username">
              <el-input v-model="passwordForm.username" placeholder="请输入用户名/邮箱">
                <template #prefix>
                  <el-icon>
                    <user/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="passwordForm.password" type="password" placeholder="请输入密码">
                <template #prefix>
                  <el-icon>
                    <lock/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handlePasswordLogin" :loading="loading">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="手机号登录" name="sms">
          <el-form :model="smsForm" :rules="smsRules" ref="smsFormRef">
            <el-form-item prop="phone">
              <el-input v-model="smsForm.phone" placeholder="请输入手机号">
                <template #prefix>
                  <el-icon>
                    <iphone/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="code">
              <verify-code-input
                  v-model="smsForm.code"
                  :phone="smsForm.phone"
                  @send-code="sendSmsCode"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSmsLogin" :loading="loading">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div class="login-footer">
        <div class="other-login">
          <third-party-login @login="handleThirdPartyLogin"/>
        </div>
        <div class="login-links">
          <el-link type="primary" @click="$router.push('/register')">注册账号</el-link>
          <el-link type="primary">忘记密码</el-link>
        </div>
      </div>
    </div>

    <!-- 授权确认区域 -->
    <el-drawer v-model="drawer" title="授权确认" :with-header="false" size="20%">
      <div class="authorize-box">
        <div class="authorize-header">
          <h2>授权确认</h2>
        </div>

        <div class="client-info">
          <el-avatar :size="60" :src="clientInfo.logo" />
          <h3>{{ clientInfo.name }}</h3>
          <p>请求访问您的账号信息</p>
        </div>

        <div class="scope-list">
          <h4>将获取以下权限：</h4>
          <ul>
            <li v-for="scope in clientInfo.scope" :key="scope">
              <el-icon><check /></el-icon>
              {{ scopeDescriptions[scope] || scope }}
            </li>
          </ul>
        </div>

        <div class="authorize-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="loading">同意授权</el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {User, Lock, Iphone} from '@element-plus/icons-vue'
import VerifyCodeInput from '@/components/VerifyCodeInput.vue'
import ThirdPartyLogin from '@/components/ThirdPartyLogin.vue'
import {useAuthStore} from '@/stores/auth'
import {confirmAuthorize, ConfirmParams, getAuthorizeInfo, getRedirectUri, LoginParams} from '@/api/auth'
import { ElMessage } from 'element-plus'
import defaultLogo from '@/assets/images/user.png'

// 授权确定抽屉是否限时
const drawer = ref(false)

const router = useRouter()
const route = useRoute()
const {query} = useRoute()
const authStore = useAuthStore()

const activeTab = ref('password')
const loading = ref(false)

const passwordForm = ref({
  username: '',
  password: ''
})

const smsForm = ref({
  phone: '',
  code: ''
})

const clientInfo = ref({
  name: '',
  logo: defaultLogo,
  scope: ["userinfo"]
})

const scopeDescriptions: Record<string, string> = {
  'userinfo': '基本信息（用户名、头像）'
}

// 表单验证规则
const passwordRules = {
  username: [{required: true, message: '请输入用户名/邮箱', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}]
}

const smsRules = {
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  code: [{required: true, message: '请输入验证码', trigger: 'blur'}]
}

const handlePasswordLogin = async () => {
  try {
    loading.value = true
    const params = {
      name: passwordForm.value.username,
      pwd: passwordForm.value.password,
      grant_type: 'password',
    }
    await authStore.login(params)
    tryJump(query)
  } finally {
    loading.value = false
  }
}

const handleSmsLogin = async () => {
  try {
    loading.value = true
    const params = {
      phone: smsForm.value.phone,
      code: smsForm.value.code,
      grant_type: 'sms_code',
      client_id: 'web',
      client_secret: 'secret'
    }
    await authStore.login(params)
    router.push('/user-center')
  } finally {
    loading.value = false
  }
}

const sendSmsCode = async () => {
  // 发送验证码逻辑
}

const handleThirdPartyLogin = (type: string) => {
  // 第三方登录逻辑
  window.location.href = `/oauth/authorize?client_id=${type}&redirect_uri=${encodeURIComponent(window.location.origin)}`
}

// 登录成功后调用
const fetchAuthorizeInfo = async (clientId: string) => {
  const response = await getAuthorizeInfo(clientId)
  clientInfo.value = response
  drawer.value = true
}

// 确定授权
const handleConfirm = async () => {
  try {
    loading.value = true
    const clientId = route.query.client_id as string
    const confirmParams: ConfirmParams = {
      response_type: route.query.response_type as string,
      client_id: clientId,
      redirect_uri: route.query.redirect_uri as string,
      scope: "userinfo",
      build_redirect_uri: true
    }
    const confirmRes =  await confirmAuthorize(confirmParams)
    console.log("confirmRes: ", JSON.stringify(confirmRes))
    window.location.href = confirmRes.redirect_uri as string
  } finally {
    loading.value = false
  }
}

// 取消授权
const handleCancel = () => {
  window.location.href = `${route.query.redirect_uri}?error=access_denied`
}

const tryJump = async (query: any) => {
  if(!query.hasOwnProperty("client_id")){
    query = {
      client_id: "platform",
      scope: "userinfo",
      redirect_uri: "http://127.0.0.1:8080/home",
      response_type: "code"
    }
  }
  const jumpRes = await getRedirectUri(query)
  // 未登录的情况
  if (jumpRes.code === 401) {
    setTimeout(function () {
      router.push({path: '/', query})
    }, 800);
    return
  }
  // 已登录，需要用户手动授权的情况
  if (jumpRes.code === 411) {
    clientInfo.value.scope = query.scope.split(',')
    drawer.value = true
    return
  }
  // 已登录，无需用户手动确定授权
  if(jumpRes.code == 200) {
    location.href = jumpRes.redirect_uri;
    return;
  }
  console.log('未知状态码，', jumpRes.code, jumpRes);
  ElMessage.error(jumpRes.msg || '请求失败')
}

onMounted(() => {
  tryJump(query)
})

</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #1a73e8, #0d47a1);

  .login-box {
    width: 400px;
    padding: 40px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);

    .login-header {
      text-align: center;
      margin-bottom: 30px;

      h2 {
        color: #1a73e8;
        margin-bottom: 10px;
      }

      p {
        color: #666;
      }
    }

    .el-button {
      width: 100%;
    }

    .login-footer {
      margin-top: 20px;

      .other-login {
        margin-bottom: 20px;
      }

      .login-links {
        display: flex;
        justify-content: space-between;
      }
    }
  }
}

.authorize-box {
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  //box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);

  .authorize-header {
    text-align: center;
    margin-bottom: 30px;

    h2 {
      color: #1a73e8;
    }
  }

  .client-info {
    text-align: center;
    margin-bottom: 30px;

    h3 {
      margin: 10px 0;
    }

    p {
      color: #666;
    }
  }

  .scope-list {
    margin-bottom: 30px;

    h4 {
      margin-bottom: 15px;
      color: #333;
    }

    ul {
      list-style: none;
      padding: 0;

      li {
        padding: 8px 0;
        display: flex;
        align-items: center;

        .el-icon {
          color: #1a73e8;
          margin-right: 10px;
        }
      }
    }
  }

  .authorize-actions {
    display: flex;
    justify-content: space-between;

    .el-button {
      width: 48%;
    }
  }
}

</style>